import { login, userGetInfoApi } from '@/api'
export default {
  namespaced: true,
  state: {
    token: JSON.parse(localStorage.getItem('dkdToken')) || '',
    id: JSON.parse(localStorage.getItem('id')) || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || ''
  },
  mutations: {
    // 保存token
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('dkdToken', JSON.stringify(token))
    },
    SET_ID(state, id) {
      state.id = id
      localStorage.setItem('id', JSON.stringify(id))
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    CLEAR_TOKEN(state) {
      state.token = ''
      state.id = ''
      state.userInfo = ''
      localStorage.removeItem('dkdToken')
      localStorage.removeItem('id')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    // 调用登录接口，获取token
    async fetchLogin(store, loginForm) {
      try {
        const res = await login(loginForm)
        // console.log(res)
        store.commit('SET_TOKEN', res.token)
        store.commit('SET_ID', res.userId)
        return Promise.resolve(res)
      } catch (err) {
        return Promise.reject(err)
      }
    },
    async fetchUserInfo(store) {
      const res = await userGetInfoApi(store.state.id)
      // console.log(res)
      store.commit('SET_USERINFO', res)
    }
  }
}
